package com.slipper.system.role.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.system.role.dao.RoleDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.slipper.system.api.role.bo.RoleBO;
import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.Tool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@ReadTransactional
public class RoleService {
    @Resource
    private RoleDao roleDao;
    
    public RoleBO queryBy(RoleBO bo){
        return roleDao.queryBy(bo);
    }
    
    public PageInfo<RoleBO> queryPage(RoleBO bo){
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(roleDao.queryList(bo));
    }
    
    @WriteTransactional
    public Integer save(RoleBO bo){
        if (bo.getId() != null && !"".equals(bo.getId())) {
            return roleDao.update(bo);
        } else {
            bo.setId(Tool.getUUID());
            return roleDao.insert(bo);
        }
    }
    
    @WriteTransactional
    public Integer delete(RoleBO bo){
        return roleDao.delete(bo);
    }

    public Boolean isSuperAdmin(String employeeId) {
        RoleBO bo = new RoleBO();
        bo.setEmployeeId(employeeId);
        bo.setPower(0);
        return this.roleDao.queryRoleCnt(bo) > 0;
    }

    public boolean isUse(String id) {
        return this.roleDao.queryUseCnt(id) > 0;
    }
    
    public List<RoleBO> queryByUserId(String employeeId) {
        return this.roleDao.queryByEmployeeId(employeeId);
    }

    public List<RoleBO> queryList(RoleBO bo) {
        return roleDao.queryList(bo);
    }

    public List<String> queryPower(RoleBO bo) {
        return this.roleDao.queryPower(bo);
    }

    public Integer savePower(RoleBO bo) {
        int result = this.roleDao.deletePower(bo.getId());
        List<Map<String, String>> dataList = new ArrayList<>();
        if (bo.getPrivilegeIds() != null) {
            for (String privilegeId : bo.getPrivilegeIds()) {
                String[] menuPrivilegeId = privilegeId.split("--");
                Map<String, String> dataMap = new HashMap<>();
                dataMap.put("id", Tool.getUUID());
                dataMap.put("roleId", bo.getId());
                dataMap.put("menuId", menuPrivilegeId[0]);
                dataMap.put("privilegeId", menuPrivilegeId[1]);
                dataList.add(dataMap);
            }
        }
        if (!dataList.isEmpty()) {
            result += this.roleDao.savePower(dataList);
        }
        return result;
    }

    public List<RoleBO> queryPermitRole(RoleBO bo) {
        return this.roleDao.queryPermitRole(bo);
    }
}
